<template>
  <a-modal :open="isOpen" :title="props.editData.userId ? '编辑' : '新增'" @ok="handleAddEdit" @cancel="onCancel">
    <a-form ref="formRef" :model="addObj">
      <a-form-item
        label="用户名"
        name="userName"
        :rules="[
          { required: true, message: '请输入用户名' },
          { max: 10, message: '最多输入10个字符' },
        ]"
      >
        <a-input v-model:value="addObj.userName"></a-input>
      </a-form-item>
      <a-form-item
        label="手机号"
        name="userPhone"
        :rules="[
          { required: true, message: '请输入手机号' },
          { len: 11, message: '请输入11位手机号' },
        ]"
      >
        <a-input v-model:value="addObj.userPhone"></a-input>
      </a-form-item>
      <a-form-item label="状态" name="userStatus" :rules="[{ required: true, message: '请选择人员状态' }]">
        <a-select v-model:value="addObj.userStatus" :options="userStatusOptions" optionLabelProp="label" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, defineEmits, defineProps, watchEffect } from 'vue';
import UserManage from '@/api/user';
import { message } from 'ant-design-vue';
const emits = defineEmits(['cancel', 'success']);

// 接收父组件
const formRef = ref(null);
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,
  },
  editData: {
    type: Object,
  },
});
const addObj = ref(props.editData ? { ...props.editData } : {});

// onCancel 事件
const onCancel = () => {
  emits('cancel');
  formRef.value.resetFields();
};

const handleAddEdit = async () => {
  // 先对数据进行校验
  await formRef.value.validateFields();
  // 判断是否有id
  const isEdit = !!addObj.value.userId;

  console.log(addObj.value.userStatus);

  if (isEdit) {
    await UserManage.editUser(addObj.value);
    // debugger;
    console.log(addObj.value);

    message.success('编辑成功');
  } else {
    await UserManage.addUser(addObj.value);
    message.success('新增成功');
  }
  emits('success');
  formRef.value.resetFields();
};

// 定义选项
const userStatusOptions = [
  { label: '启用', value: 1 },
  { label: '停用', value: 0 },
];

// 监听 editData 的变化
watchEffect(() => {
  addObj.value = { ...props.editData };
});
</script>

<style></style>
